using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using FileTransferDesktop.Views.Windows;
using Microsoft.Extensions.DependencyInjection;
using Wpf.Ui.Tray.Controls;
using NotifyIcon = Wpf.Ui.Tray.Controls.NotifyIcon;

namespace FileTransferDesktop.Services;

/// <summary>
/// 系统托盘服务实现
/// </summary>
public class TrayService : ITrayService, IDisposable
{
    private NotifyIcon? _notifyIcon;
    private bool _disposed = false;

    public void Initialize()
    {
        try
        {
            _notifyIcon = new NotifyIcon
            {
                TooltipText = "FileTransfer Desktop",
                Icon = new BitmapImage(new("pack://application:,,,/Assets/file_transfer1.png")),
                ContextMenu = CreateDefaultContextMenu(),
            };

            _notifyIcon.LeftClick += OnTrayIconLeftClick;
            _notifyIcon.RightClick += OnTrayIconRightClick;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"托盘初始化失败: {ex.Message}");
        }
    }

    public void Show()
    {
        if (_notifyIcon != null)
        {
            _notifyIcon.Visibility = Visibility.Visible;
        }
    }

    public void Hide()
    {
        if (_notifyIcon != null)
        {
            _notifyIcon.Visibility = Visibility.Collapsed;
        }
    }

    public void UpdateTooltip(string tooltip)
    {
        if (_notifyIcon != null)
        {
            _notifyIcon.TooltipText = tooltip;
        }
    }

    public void UpdateMenu(ContextMenu menuItems)
    {
        if (_notifyIcon != null)
        {
            _notifyIcon.ContextMenu = menuItems;
        }
    }

    public void ShowBalloonTip(string title, string message, int timeout = 3000)
    {
        if (_notifyIcon != null)
        {
            //_notifyIcon.ShowBalloonTip(title, message, timeout);
        }
    }

    private ContextMenu CreateDefaultContextMenu()
    {
        var contextMenu = new ContextMenu();

        // 显示主窗口
        var showMenuItem = new MenuItem
        {
            Header = "显示主窗口",
            Icon = new Wpf.Ui.Controls.SymbolIcon
            {
                Symbol = Wpf.Ui.Controls.SymbolRegular.WindowNew20,
            },
        };
        showMenuItem.Click += (_, _) => ShowMainWindow();
        contextMenu.Items.Add(showMenuItem);

        // 分隔符
        contextMenu.Items.Add(new Separator());

        // 上传文件
        var uploadMenuItem = new MenuItem
        {
            Header = "上传文件",
            Icon = new Wpf.Ui.Controls.SymbolIcon
            {
                Symbol = Wpf.Ui.Controls.SymbolRegular.CloudArrowUp20,
            },
        };
        uploadMenuItem.Click += (_, _) => NavigateToPage("Upload");
        contextMenu.Items.Add(uploadMenuItem);

        // 下载文件
        var downloadMenuItem = new MenuItem
        {
            Header = "下载文件",
            Icon = new Wpf.Ui.Controls.SymbolIcon
            {
                Symbol = Wpf.Ui.Controls.SymbolRegular.CloudArrowDown20,
            },
        };
        downloadMenuItem.Click += (_, _) => NavigateToPage("Download");
        contextMenu.Items.Add(downloadMenuItem);

        // 文件管理
        var managementMenuItem = new MenuItem
        {
            Header = "文件管理",
            Icon = new Wpf.Ui.Controls.SymbolIcon
            {
                Symbol = Wpf.Ui.Controls.SymbolRegular.FolderOpen24,
            },
        };
        managementMenuItem.Click += (_, _) => NavigateToPage("Management");
        contextMenu.Items.Add(managementMenuItem);

        // 分隔符
        contextMenu.Items.Add(new Separator());

        // 设置
        var settingsMenuItem = new MenuItem
        {
            Header = "设置",
            Icon = new Wpf.Ui.Controls.SymbolIcon
            {
                Symbol = Wpf.Ui.Controls.SymbolRegular.Settings24,
            },
        };
        settingsMenuItem.Click += (_, _) => NavigateToPage("Settings");
        contextMenu.Items.Add(settingsMenuItem);

        // 分隔符
        contextMenu.Items.Add(new Separator());

        // 退出
        var exitMenuItem = new MenuItem
        {
            Header = "退出",
            Icon = new Wpf.Ui.Controls.SymbolIcon
            {
                Symbol = Wpf.Ui.Controls.SymbolRegular.Power24,
            },
        };
        exitMenuItem.Click += (_, _) => ExitApplication();
        contextMenu.Items.Add(exitMenuItem);

        return contextMenu;
    }

    private void OnTrayIconLeftClick(NotifyIcon sender, RoutedEventArgs e)
    {
        ShowMainWindow();
    }

    private void OnTrayIconRightClick(NotifyIcon sender, RoutedEventArgs e)
    {
        // 右键点击时显示上下文菜单（WPF-UI.Tray会自动处理）
    }

    private void ShowMainWindow()
    {
        try
        {
            var mainWindow = App.Services?.GetService<MainWindow>();
            if (mainWindow != null)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (mainWindow.WindowState == WindowState.Minimized)
                    {
                        mainWindow.WindowState = WindowState.Normal;
                    }

                    mainWindow.Show();
                    mainWindow.Activate();
                    mainWindow.Focus();
                });
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"显示主窗口失败: {ex.Message}");
        }
    }

    private void NavigateToPage(string pageName)
    {
        try
        {
            ShowMainWindow();

            var mainWindow = App.Services?.GetService<MainWindow>();
            if (mainWindow != null)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Type? pageType = pageName switch
                    {
                        "Upload" => typeof(Views.Pages.UploadPage),
                        "Download" => typeof(Views.Pages.DownloadPage),
                        "Management" => typeof(Views.Pages.ManagementPage),
                        "Settings" => typeof(Views.Pages.SettingsPage),
                        _ => typeof(Views.Pages.DashboardPage),
                    };

                    if (pageType != null)
                    {
                        mainWindow.Navigate(pageType);
                    }
                });
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"导航到页面失败: {ex.Message}");
        }
    }

    private void ExitApplication()
    {
        Application.Current.Dispatcher.Invoke(() =>
        {
            Application.Current.Shutdown();
        });
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed && disposing)
        {
            if (_notifyIcon != null)
            {
                _notifyIcon.LeftClick -= OnTrayIconLeftClick;
                _notifyIcon.RightClick -= OnTrayIconRightClick;
                _notifyIcon.Dispose();
                _notifyIcon = null;
            }
            _disposed = true;
        }
    }
}
